package com.java2104.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileUploadController {
    //上传的图片保存的服务器路径
    private static final String UPLOAD_PATH = "D:/image/";

    //处理上传图片的请求
    @RequestMapping("/upload")
    @ResponseBody
    public Map upload(@RequestParam("faceImg") MultipartFile multipart) throws IOException {
        String oldFilename = multipart.getOriginalFilename();//获取其原来的文件名 例如：小二郎.jpg
        long size = multipart.getSize();//获取上传图片的大小（字节为单位）
        InputStream is = multipart.getInputStream();//获取文件的输入流
        String contentType = multipart.getContentType();//获取上传文件的格式
        if (!new File(UPLOAD_PATH).exists()) {//如果保存上传图片的文件目录不存在
            new File(UPLOAD_PATH).mkdirs();//新建这个文件目录
        }
        FileOutputStream fos = new FileOutputStream(UPLOAD_PATH + oldFilename);//创建文件输出流

        FileCopyUtils.copy(is, fos);//将上传文件保存到指定的位置
        Map map = new HashMap();
        map.put("filename", oldFilename);
        map.put("size", size);
        map.put("contentType", contentType);
        map.put("status", "ok");
        map.put("accessPath", "<a href='/image/" +oldFilename+ "'>查看图片</a>");
        return map;
    }

    @GetMapping("/upload")
    public String upload() {
        return "fileupload";
    }

    @GetMapping("/image/{filename}")
    public void fileDownload(@PathVariable("filename") String filename,
                             HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String uri = req.getRequestURI();// /image/lbxx.jpg
        String suffix = uri.substring(uri.lastIndexOf("."));//.jpg
        //获取访问文件的输出流
        FileInputStream fis = new FileInputStream(UPLOAD_PATH + filename + suffix);
        FileCopyUtils.copy(fis, resp.getOutputStream());//返回文件内容
    }

}
